package com.msun.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.msun.constant.MessageConstant;
import com.msun.dao.MemberDao;
import com.msun.dao.OrderDao;
import com.msun.dao.SetmealDao;
import com.msun.dao.UserDao;
import com.msun.entity.PageResult;
import com.msun.entity.QueryPageBean;
import com.msun.entity.Result;
import com.msun.pojo.Member;
import com.msun.pojo.Order;
import com.msun.pojo.Setmeal;
import com.msun.pojo.User;
import com.msun.service.MemberService;
import com.msun.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 会员服务
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private UserDao userDao;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }
    @Override
    // 分页查询会员信息
    public PageResult findPage(QueryPageBean queryPageBean) {
        // 当前页
        Integer currentPage = queryPageBean.getCurrentPage();
        // 当前页大小
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        // 执行分页查询获取到会员信息
        PageHelper.startPage(currentPage,pageSize);
        Page<Member> page = memberDao.selectByCondition(queryString);
        List<Member> result = page.getResult();
        for (Member member : result) {
            User user = userDao.findUserByMemberId(member.getId());
            member.setHealthManager(user==null?null:user.getId());
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void addMember(Member member) {
        //设置会员注册时间为当前日期
        member.setRegTime(new Date());
        String password = member.getPassword();
        if(password != null){
            //使用md5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        // 添加会员主体信息
        memberDao.add(member);

        if (member.getHealthManager()!=null){
            // 添加会员和健康管理师的关联关系信息
            userDao.addUserMemberHealthMamgerRefer(member.getId(),member.getHealthManager());
        }

    }

    @Override
    public void edit(Member member) {
        // 先删除对应的关系
        userDao.deleteReferByMemberId(member.getId());
        // 在编辑主体
        memberDao.edit(member);
        // 添加关系信息
        userDao.addUserMemberHealthMamgerRefer(member.getId(),member.getHealthManager());
    }

    @Override
    public void delete(Integer id) {
        // 查询在订单表中是否有被关联的信息
        List<Order> orders = orderDao.findByMemberId(id);
        if (orders!=null&&orders.size()>0){
            String message = "会员信息被引用!";
            for (Order order : orders) {
                message +="<br/>订单编号:"+order.getId();
            }
            // 会员信息被引用了
            throw new RuntimeException(message);
        }
        // 删除健康管理师绑定
        userDao.deleteReferByMemberId(id);
        memberDao.deleteById(id);
    }

    @Override
    public Member findByPhone(String tel) {
        return memberDao.findByTelephone(tel);
    }

    //保存会员信息
    @Override
    public void add(Member member) {
        String password = member.getPassword();
        if(password != null){
            //使用md5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    //根据月份查询会员数量
    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {//2018.05
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";//2018.05.31
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }

    @Override
    public void update(Member member) {
        memberDao.edit(member);
    }

    @Override
    public Result savePwd(Map<String, String> map) {
        // 数据库中的密码
        String oldPwdInDb = map.get("oldPwdInDb");
        // 用户输入的旧密码
        String oldPwd = map.get("oldPwd");
        // 用户输入的新密码
        String newPwd = map.get("newPwd");
        if (oldPwdInDb!=null){
            //对比用户输入旧密码和数据库中的旧密码是否一致
            String oldPwdMd5 = null;
            try {
                oldPwdMd5 = MD5Utils.md5(oldPwd);
            } catch (Exception e){

            }

            if (oldPwdMd5==null||!oldPwdMd5.equals(oldPwdInDb)){
                return new Result(false, MessageConstant.UPDATE_PASSWORD_FAIL_UNI);
            }
        }

        String memberId = map.get("memberId");
        Member member =new Member();
        member.setId(Integer.parseInt(memberId));
        member.setPassword(MD5Utils.md5(newPwd));
        memberDao.edit(member);
        return new Result(true, MessageConstant.UPDATE_PASSWORD_SUCCESS);
    }

    @Override
    public List<Map<String, Object>> findHistorySetmeal(Map<String,Object> map) {

        Member member = (Member) map.get("member");
        String start = (String) map.get("start");
        String end = (String) map.get("end");
        // 给dao拼接参数
        Map<String,String> parMap =new HashMap<>();
        parMap.put("start",start);
        parMap.put("end",end);
        parMap.put("memberId",member.getId().toString());
        List<Order> list = orderDao.findHisSetmeal4Date(parMap);
        //要返回的结果集合
        List<Map<String, Object>> result = new ArrayList<>();
        for (Order order : list) {
            Map<String, Object> inMap = new HashMap<>();
            // 让对象不自动引用 https://blog.csdn.net/weixin_42802934/article/details/107808394
            String memberStr = JSON.toJSONString(member, SerializerFeature.DisableCircularReferenceDetect);
            Member memberS = JSON.parseObject(memberStr, Member.class);
            inMap.put("member",memberS);
            String orderStr = JSON.toJSONString(order, SerializerFeature.DisableCircularReferenceDetect);
            Order orderS = JSON.parseObject(orderStr, Order.class);
            inMap.put("order",orderS);
            Setmeal setmeal = setmealDao.findById(order.getSetmealId());
            String setmealStr = JSON.toJSONString(setmeal, SerializerFeature.DisableCircularReferenceDetect);
            Setmeal setmealS = JSON.parseObject(setmealStr, Setmeal.class);
            inMap.put("setmeal",setmealS);
            result.add(inMap);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> findMemberAge() {
        List<Map<String,Object>> list= memberDao.findMemberAge();
        return list;

    }

    @Override
    public List<Map<String, Object>> findSetmealIncomeByDate(String dBegin, String dEnd) {
        List<Map<String, Object>> list=  memberDao.findSetmealIncomeByDate(dBegin,dEnd);

        return list;
    }

    @Override
    public Member findMemberById(Integer id) {
        Member member= memberDao.findMemberById(id);
        return member;
    }
    @Override
    public Member findMemberByMemberId(Integer id){
        return memberDao.findById(id);
    }
}
